<template>
  <div class="jq-table h-full flex-col">
    <SearchForm
      @handle-reset-form-datas="handleResetFormDatas"
      :searchForm="searchForm"
      @handle-search="handleSearch"
    />
    <div class="page-card h-full" v-loading="loading">
      <JqTable
        :tableColumn="tableColumn"
        :tableButtons="tableButtons"
        :itemsButtons="itemsButtons"
        :data="tableData"
        :page="page"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      <template #status>
          <el-table-column show-overflow-tooltip :min-width="80" prop="visible" label="状态" fit="true" show-header="true"
            align="left">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <!-- <el-switch v-model="scope.row.visible" :active-value="0" :inactive-value="1"
                  @change="setIs('visible', scope.row)" /> -->
                <span :class="scope.row.status === 1 ? 'point1' : 'point2'"></span>
                <span>{{ scope.row.status === 1 ? '启用' :  '停用' }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
      </JqTable>

      <AddOrUpdate
        v-if="showDialog"
        v-model:dialogVisible="showDialog"
        ref="addOrUpdateRef"
        :dialogDatas="dialogDatas"
        @update-list="updateList"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
defineOptions({ name: 'SystemRole' }); //角色管理
import { reactive, ref, onMounted, computed } from 'vue';
import { useTable } from '@/hooks/useTable';
import { roleList, roleDeleteRequest, roleStatusRequest } from '@/api/system/role/index'; //api
// import type { IUserItem } from '@/api/system/role/type';
import { JqTable } from '@/components/Table/index';
import { AddOrUpdate } from './components';
import { useRoute, useRouter } from 'vue-router';
import { orgOptionsRequest, enumListRequest } from '@/api/common';
import { useRouteStore } from '@/store';
const routeStore = useRouteStore();
const router = useRouter();
const showDialog = ref(false);
const addOrUpdateRef = ref();
let orgIdDatas = reactive([]);
let roleEnumList = reactive([]);
let searchFormParams = reactive({}); //查询参数
const currentMenudatas = computed(() => routeStore.currentMenudatas);
let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '角色查询',
    placeholder: '请输入角色查询',
    eName: 'roleName'
  },
  {
    type: 'select',
    value: '',
    label: '归属组织',
    placeholder: '全部',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'select',
    value: '',
    label: '角色状态',
    options: () => {
      return roleEnumList;
    },
    eName: 'roleStatus'
  }
]);

let dialogConfig = {
  id: 5,
  roleName: '',
  orgId: '',
  dataScope: 0,
  remark: '',
  menuIdList: {
    menuListMap: [
      {
        id: 0,
        parentId: 0,
        menuName: '检测点管理',
        isCheck: false,
        children: [
          {
            id: 1,
            parentId: 0,
            menuName: '删除',
            isCheck: false,
            children: [{}]
          },
          {
            id: 2,
            parentId: 3,
            menuName: '查看',
            isCheck: false,
            children: [{}]
          }
        ]
      }
    ]
  }
};

const tableColumn = reactive([
  { label: '角色名称', prop: 'roleName', minWidth: '80' },
  { label: '归属组织机构', prop: 'orgName', minWidth: '140' },
  { label: '创建时间', prop: 'createTime', minWidth: '170' },
  { label: '角色拥有人数', prop: 'usedNumber', minWidth: '140' },
  { label: '状态', prop: 'status', minWidth: '80', slot: true }
]);
let tableButtons = reactive([
  {
    id: 54,
    type: 'primary',
    label: '添加',
    perms: 'sys:role:btn:create',
    onClick: () => {
      showDialog.value = true;
      dialogDatas = {
        title: '新增',
        type: 'add',
        datas: dialogConfig
      };
      // const data = dialogConfig;
      // resetAddDialogDatas(data);
      // onAddOrUpdate(dialogDatas);
    }
  }
]);

let itemsButtons = reactive([
  {
    id: 52,
    type: 'primary',
    label: '查看',
    perms: 'sys:role:btn:view',
    onClick: (row: any) => {
      showDialog.value = true;
      dialogDatas = {
        title: '查看',
        type: 'check',
        datas: row
      };
      // onAddOrUpdate(dialogDatas);
    }
  },
  {
    id: 53,
    type: 'primary',
    label: '编辑',
    perms: 'sys:role:btn:edit',
    onClick: (row) => {
      showDialog.value = true;
      dialogDatas = {
        title: '编辑',
        type: 'edit',
        datas: row
      };
      // onAddOrUpdate(dialogDatas);
    }
  },
  {
    id: 55,
    eName: 'pause',
    perms: 'sys:role:btn:status',
    statusConfig: {
      1: '启用',
      2: '停用'
      // 3:'待激活'
    },
    onClick: async (row: any) => {
      await roleStatusRequest({ id: row.id });
      ElMessage.success('修改成功');
      getList();
    }
  },
  // {
  //   eName: 'stop3',
  //   id: 55,
  //   type: 'warning',
  //   onClick: async (row: any) => {
  //     await roleStatusRequest({ id: row.id });
  //     getList();
  //   }
  // },
  {
    id: 56,
    type: 'danger',
    perms: 'sys:role:btn:del',
    label: '删除',
    onClick: (row) => {
      deleteFun(row);
    }
  }
]);
let dialogDatas = reactive({});
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: roleList,
    params: () => searchFormParams
  });

const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
// 组织下拉
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: true });
  orgIdDatas = data.data;
};
// 角色下拉
const getRoleEnumList = async () => {
  const data: any = await enumListRequest({ enumName: 'RoleStatusEnum' });
  roleEnumList = data.data;
};
// 数据筛选
const handleSearch = async (searchFormParamsDatats: {}) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  await getList();
};
const updateList = () => {
  getList();
  showDialog.value = false;
};
// 删除
const deleteFun = (rowData: any) => {
  ElMessageBox.confirm('是否删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const data: any = await roleDeleteRequest({ id: rowData.id });
    if (data.code === 2000) {
      ElMessage.success('删除成功');
      getList();
    } else {
      ElMessage.error(data?.message);
      return;
    }
    return;
  });
  // .catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: '取消操作'
  //   });
  // });
};
onMounted(() => {
  if(!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value?.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value?.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
});
/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams = {};
  searchForm = searchForm.map((item) => {
    if (item.value) {
      item.value = '';
    }
    return item;
  });
  getList();
};
getRoleEnumList();
getOrgOptionsDatas();
</script>
<style scoped></style>
